<template>
	<view class="container">
		<!-- 底层地图 -->
		<!-- #ifdef APP-PLUS -->
		<view class="map-contarin">
			<map id="pathDetailMap" class="map-content" ref="pathDetailMap" 
			:style="{width:'750rpx',height:windowHeight}" 
			:latitude="latitude" :longitude="longitude" 
			:markers="markers" 
			:polyline="polyline" 
			:enable-rotate="true" 
			:enable-overlooking="true" 
			:enable-traffic="true" 
			@markertap="markerTap" 
			:showLocation="showLocation" 
			:scale="scale">
				<cover-image class="map-btn rest-btn" @click="refreshHandel" src="@/static/images/bus/rest.png"></cover-image>
			</map>
		</view>
		<!-- #endif -->
		
		<!-- #ifdef MP || H5 -->
		<view class="map-contarin">
			<map id="pathDetailMap" class="map-content" ref="pathDetailMap" 
			:style="{width:'750rpx',height:'100vh'}"
			:latitude="latitude" :longitude="longitude" 
			:markers="markers" 
			:polyline="polyline" 
			:enable-rotate="true" 
			:enable-overlooking="true" 
			:enable-traffic="true" 
			@markertap="markerTap" 
			:showLocation="showLocation" 
			:scale="scale">
				<cover-image class="map-btn rest-btn" @click="refreshHandel" src="@/static/images/bus/rest.png"></cover-image>
			</map>
		</view>
		<!-- #endif -->
	</view>
</template>

<script>
	import request from '@/common/js/xrRequest.js' //请求封装
	import {
		getLineDetails,
		busInfo
	} from '@/common/js/xrApi.js' //请求地址
	export default {
		data() {
			return {
				lineId:'',//线路id
				lineName:'',//线路名称
				stationId:'',//站点id
				stationName:'',//站点名称
				// 当前位置经纬度-搜索公交线路页进详情使用
				curLocation: {
					latitude: '',
					longitude: ''
				},
				// 地图
				latitude: '',
				longitude: '',
				showLocation: true,
				scale: 14, //地图缩放级别
				
				windowWidth: 750, //设备可使用窗口宽度
				windowHeight: 0, //设备可使用窗口宽度
				statusBarHeight: 0, //状态栏高
				
				lineRawData: {}, //线路原始数据
				realBusList: [], //实时原始公交数据
				
				lineBascInfo: {
					drivingDirection: 1, //行驶方向 1.上行  2.下行 3.环形
					lineName: '', //线路名
					startStationName: '起始站', //起点站
					endStationName: '终点站', //终点站
					firstTime: '6:30', //首班发车时间
					lastTime: '22:00', //末班发车时间
					ticketPrice: '2', //票价
					totalMileage: '9.6' //线路全程距离
				},
				
				stationsList: [], //站点列表
				selectStation: {}, //选中的站点
				selectStationIndex: 1, //选中的站点索引
				
				carList: [], //车辆列表
				effectiveCarList: [], //未过目标站点的列表
				noBusData: false,
				
				markers: [], //所有标注
				stationMarkers: [], //站点标注
				carMarkers: [], //车辆标注
				selectStationMarkers: [], //选中站点标注，只能选中一个
				
				points: [], //线路点
				polyline: [], //线路
				
				setInterNameMap: null //定时器对象
			}
		},
		onLoad(option) {
			// 公交线路
			this.lineId = option.lineId;
			this.lineName = option.lineName;
			uni.setNavigationBarTitle({
				title:this.lineName
			})
			// 公交方向
			this.lineBascInfo.drivingDirection = option.drivingDirection;
			// 站点信息
			this.selectStationIndex = option.selectStationIndex;
			this.selectStation = JSON.parse(option.selectStation);
			this.latitude = this.selectStation.latitude,
			this.longitude = this.selectStation.longitude
			
			this.getLineDetails();
			
		},
		onShow() {
			let that = this;
			// 获取屏幕高度
			uni.getSystemInfo({
				success: function(res) {
					that.windowWidth = res.windowWidth;
					that.windowHeight = res.windowHeight - 64;
				}
			});
			// 定时获取实时数据
			this.setInterNameMap = setInterval(() => {
				if(that.selectStation.stationId !== undefined
				&& that.selectStation.stationId !== null){
					that.getRealBus();
				}
			}, 15000)
		},
		filters: {
			distanceFormat(val) {
				if (val < 1000) {
					return val.toFixed(0) + '米';
				} else {
					let distance = val / 1000;
					return distance.toFixed(1) + '公里';
				}
		
			}
		
		},
		watch: {
			selectStationIndex(index) { //站点列表滚动中心
				if (this.selectStationIndex <= 3) {
					this.scrollLeft = 'bus_0';
				} else if (parseInt(this.stationsList.length - 3) <= this.selectStationIndex) {
					this.scrollLeft = 'bus_' + this.selectStationIndex;
				} else {
					this.scrollLeft = 'bus_' + parseInt(this.selectStationIndex - 3);
				}
			}
		},
		onUnload() {
			clearInterval(this.setInterNameMap);
		},
		onHide() {
			clearInterval(this.setInterNameMap);
		},
		methods: {
			// 获取线路信息
			getLineDetails() {
				let that = this;
				let header = {
					"content-type": "application/json",
					"Authorization": "Bearer " + uni.getStorageSync('token')
				};
				request({
					url: getLineDetails,
					data: {
						"lineId": that.lineId
					},
					header: header,
					isShowLoading: true,
					lodingText: '加载中...'
				}).then(res => {
					// console.log(JSON.stringify(res));
					if (res.code == 200) {
						that.lineRawData = res.data;
						// 初始化线路基本信息
						that.initLineBascInfo();
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						})
					}
				}).catch(err => {
					console.log(JSON.stringify(err));
				});
			},
			getRealBus(isShowLoading) { //获取实时公交信息
				if(isShowLoading !== true){
					isShowLoading = false;
				}
				let that = this;
				let header = {
					"content-type": "application/json",
					"Authorization": "Bearer " + uni.getStorageSync('token')
				};
				request({
					url: busInfo,
					data: {
						"lineId": that.lineId,
						"stationId": that.selectStation.stationId
					},
					header: header,
					isShowLoading:isShowLoading,
					lodingText: '正在刷新...'
				}).then(res => {
					// console.log(JSON.stringify(res));
					if (res.code == 200) {
						that.realBusList = res.data;
						this.filterBusData();
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						})
					}
					// console.log(JSON.stringify(res));
				}).catch(err => {
					console.log(JSON.stringify(err));
				});
			},
			// 过滤公交车辆实时数据
			filterBusData() {
				let that = this;
				that.carList = [];
				that.effectiveCarList = [];
				that.carMarkers = [];
			
				this.realBusList.forEach(val => {
					if (that.lineBascInfo.drivingDirection == "3") { //环线
						that.carList.push(val);
						if (val.targetStationCount >= 0) { //在目标站点前的车辆
						
							// 到站时间计算
							let speed = val.speed.toFixed(0);
							let targetStationDistance = val.targetStationDistance.toFixed(0);
							
							if(speed>0 && targetStationDistance>0){
								let time = targetStationDistance/speed;
								let timeSeconds = time.toFixed(0) / 60;
								val.targetStationTime = timeSeconds.toFixed(0);
							}
							that.effectiveCarList.push(val)
							
							let calloutContent = ''
							
							if (targetStationDistance < 1000) {
								if (targetStationDistance < 30) {
									calloutContent = '已抵达'+that.selectStation.stationName;
								}else{
									calloutContent = targetStationDistance + '米后抵达'+that.selectStation.stationName;
								}
								
							} else {
								let distance = targetStationDistance / 1000;
								calloutContent = distance.toFixed(1) + '公里后抵达'+that.selectStation.stationName;
							}
							
							that.carMarkers.push({
								busNum: val.busNum,
								latitude: val.busLocation.split(',')[0],
								longitude: val.busLocation.split(',')[1],
								iconPath: '/static/images/bus/bus-2.png',
								width: 28,
								height: 34,
								anchor: {
									x: .5,
									y: 1
								},
								// rotate: val.azimuth,
								callout: {
									content: calloutContent,
									bgColor: "#000000aa",
									fontSize: 14,
									color: "#ffffff",
									borderRadius: 3,
									display: "ALWAYS",
									textAlign: "center",
									padding: 10
								}
							})
						
						}else{
							that.carMarkers.push({
								busNum: val.busNum,
								latitude: val.busLocation.split(',')[0],
								longitude: val.busLocation.split(',')[1],
								iconPath: '/static/images/bus/bus-2.png',
								width: 28,
								height: 34,
								anchor: {
									x: .5,
									y: 1
								}
							})
						}
						
					} else if (val.drivingDirection == that.lineBascInfo.drivingDirection) { //过滤出同向数据
						that.carList.push(val);
						
						if (val.targetStationCount >= 0) { //在目标站点前的车辆
						
							// 到站时间计算
							let speed = val.speed.toFixed(0);
							let targetStationDistance = val.targetStationDistance.toFixed(0);
							
							if(speed>0 && targetStationDistance>0){
								let time = targetStationDistance/speed;
								let timeSeconds = time.toFixed(0) / 60;
								val.targetStationTime = timeSeconds.toFixed(0);
							}					
							that.effectiveCarList.push(val)
							
							let calloutContent = ''
							
							if (targetStationDistance < 1000) {
								if (targetStationDistance < 30) {
									calloutContent = '已抵达'+that.selectStation.stationName;
								}else{
									calloutContent = targetStationDistance + '米后抵达'+that.selectStation.stationName;
								}
								
							} else {
								let distance = targetStationDistance / 1000;
								calloutContent = distance.toFixed(1) + '公里后抵达'+that.selectStation.stationName;
							}
							
							that.carMarkers.push({
								busNum: val.busNum,
								latitude: val.busLocation.split(',')[0],
								longitude: val.busLocation.split(',')[1],
								iconPath: '/static/images/bus/bus-2.png',
								width: 28,
								height: 34,
								anchor: {
									x: .5,
									y: 1
								},
								// rotate: val.azimuth,
								callout: {
									content: calloutContent,
									bgColor: "#000000aa",
									fontSize: 14,
									color: "#ffffff",
									borderRadius: 3,
									display: "ALWAYS",
									textAlign: "center",
									padding: 10
								}
							})
						
						}else{
							that.carMarkers.push({
								busNum: val.busNum,
								latitude: val.busLocation.split(',')[0],
								longitude: val.busLocation.split(',')[1],
								iconPath: '/static/images/bus/bus-2.png',
								width: 28,
								height: 34,
								anchor: {
									x: .5,
									y: 1
								}
							})
						}
						
					}
				})
			
				that.effectiveCarList = that.effectiveCarList.sort(that.compare('targetStationCount'));
				that.effectiveCarList.length == 0 ? that.noBusData = true : that.noBusData = false;
				that.markers = [...that.stationMarkers, ...that.carMarkers]; //...展开运算符
			},
			compare(property) { //公交排序
				return function(a, b) {
					var value1 = a[property];
					var value2 = b[property];
					return value1 - value2;
				}
			},
			//初始化线路基本信息
			initLineBascInfo() {
				// 当前方向线路
				let that = this;
				let lineArr = this.lineRawData.segments;
				let line = null;
				for (let i = 0; i < lineArr.length; i++) {
					if (lineArr[i].drivingDirection == that.lineBascInfo.drivingDirection) {
						line = lineArr[i]
					}
				}
				
				this.lineBascInfo.lineName = this.lineRawData.lineName
				
				this.lineBascInfo.firstTime = line.firstTime;
				this.lineBascInfo.lastTime = line.lastTime;
				this.lineBascInfo.ticketPrice = line.ticketPrice;
				
				//线路全程长度米转为公里 
				let totalMileage = line.totalMileage / 1000;
				this.lineBascInfo.totalMileage = totalMileage.toFixed(1);
				
				this.lineBascInfo.startStationName = line.stations[0].stationName;
				this.lineBascInfo.endStationName = line.stations[line.stations.length - 1].stationName;
				
				this.stationsList = line.stations;
				
				this.latitude = this.selectStation.latitude;
				this.longitude = this.selectStation.longitude;
				
				this.selectStation = this.stationsList[this.selectStationIndex];
				// 渲染路线和站点
				this.initPolyLine(JSON.parse(line.segmentTrajectory));
				this.initStationMarkers(line.stations);
				// 公交车实时数据
				if(that.selectStation.stationId !== undefined
				&& that.selectStation.stationId !== null){
					that.getRealBus();
				}
			},
			// 设置公交线路
			initPolyLine(segmentTrajectory) {
				let that = this
				that.polyline = []
				that.points = []
				segmentTrajectory.forEach(function(item) {
					that.points.push({
						latitude: item.latitude,
						longitude: item.longitude
					})
				})
				
				let polyline = [{ //指定一系列坐标点，从数组第一项连线至最后一项
					points: this.points,
					color: "#26a2ff", //线的颜色
					width: 9, //线的宽度
					borderColor: "#26a2ff",
					dottedLine: false,
					borderWidth: true,
					arrowLine: true, //带箭头的线 开发者工具暂不支持该属性
				}]
				that.polyline = polyline
			},
			// 处理地图标记点，站点
			initStationMarkers(stations) {
				var that = this;
				this.stationMarkers = []; //先清空
				stations.forEach((item, index) => {
					let obj = null;
					// id number类型 最大限制9位，所以不能直接使用站点id
					if (index == 0) { //开始
						obj = {
							id: index,
							latitude: item.latitude,
							longitude: item.longitude,
							iconPath: '/static/images/bus/start_point.png',
							width: 20,
							height: 20,
							anchor: {
								x: .5,
								y: 1
							},
							callout:{
								content: item.stationName,
								fontSize: 12,
								padding: 5,
								color:'#1B1B1B',
								bgColor: "#ffffff",
								borderRadius: 5,
								display: 'ALWAYS' //BYCLICK：点击显示，ALWAYS：常显示
							}
						}
					} else if (index == stations.length - 1) { //结束
						obj = {
							id: index,
							latitude: item.latitude,
							longitude: item.longitude,
							iconPath: '/static/images/bus/end_point.png',
							width: 20,
							height: 20,
							anchor: {
								x: .5,
								y: 1
							},
							callout:{
								content: item.stationName,
								fontSize: 12,
								padding: 5,
								color:'#1B1B1B',
								bgColor: "#ffffff",
								borderRadius: 5,
								display: 'ALWAYS' //BYCLICK：点击显示，ALWAYS：常显示
							}
						}
					} else { //中间
						obj = {
							id: index,
							latitude: item.latitude,
							longitude: item.longitude,
							iconPath: '/static/images/bus/bus-staion-bule.png',
							width: 18,
							height: 18,
							anchor: {
								x: .5,
								y: .5
							}
						}
						// 当前站点，修改图标，显示站点名称
						if(that.selectStationIndex == index){
							obj.iconPath = '/static/images/bus/ic-bus-stop-select.png';
							obj.width = 30;
							obj.height = 35;
							obj.anchor = {
								x: .5,
								y: .9
							};
							obj.callout = {
								content: item.stationName,
								fontSize: 12,
								padding: 5,
								color:'#ff0000',
								bgColor: "#ffffff",
								borderRadius: 5,
								display: 'ALWAYS' //BYCLICK：点击显示，ALWAYS：常显示
							}
						}
					}
					this.stationMarkers.push(obj);
				})
				this.markers = this.stationMarkers;
			},
			markerTap(e){
				// id number类型 最大限制9位
				let markerId = e.detail.markerId;
				for(var i=0;i<this.stationsList.length;i++){
					if(markerId == i){
						this.changeStation(i);
					}
				}
			},
			//切换站点
			changeStation(index) {
				this.selectStationIndex = index;
				this.selectStation = this.stationsList[index];
				this.latitude = this.selectStation.latitude;
				this.longitude = this.selectStation.longitude;
				// 刷新站点信息
				this.initStationMarkers(this.stationsList);
				this.getRealBus(true);
			},
			// 手动刷新实时数据
			refreshHandel(){
				this.getRealBus(true);
			}
		}
	}
</script>

<style>
	.container{
		position: relative;
		z-index: 1;
	}
	/* 地图 */
	.map-contarin{
		/* width: 100%;
		height: 100%; */
	}
	/* .map-content{
		width: 100vw;
		height: 100vh;
	} */
	/* .map-content{
		width: 750rpx;
		height: calc(100vh - var(--window-top));
	} */
	/* 按钮 */
	.map-btn{
		width: 100rpx;
		height: 100rpx;
	}
	.rest-btn{
		position: absolute;
		bottom: 100rpx;
		right: 20rpx;
		z-index: 9;
	}
</style>
